<template>
  <div class="heatmap-report">
    <h2>{{englishMonthList[time.month]}}天气客流展示数据

      <el-radio-group @change="tagChange" v-model="tag" size="mini">
        <el-radio-button v-for="tag in tags" :key="tag" :label="tag"></el-radio-button>
      </el-radio-group>
    </h2>
    <div class="echardiv">
      <div class="repData" id="heatmapid" v-loading="loadingimg"
           element-loading-text="拼命加载中..."
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)"

      >
        <div>
          <div class="calendar-header clear" v-show="false">
            <div class="calendar-box" v-if="this.headOptions.type == 'combination'">
              <div class="calendar-content" :style="{'text-align': this.headStyle.combination}">
                <span class="calendar-prev" @click="handlePrevMonth"> 《《 </span>
                <span class="calendar-headDate"> {{this.headOptions.date}} </span>
                <span class="calendar-next" @click="handleNextMonth"> 》》 </span>
              </div>
              <span class="calendar-today" @click="handleToday()"> 今天 </span>
            </div>
            <div class="calendar-box" v-else>
              <span class="calendar-headDate"> {{this.headOptions.date}} </span>
              <span class="calendar-today dispersion-today" :style="{float: this.headStyle.todayBtn}"
                    @click="handleToday()"> 今天 </span>
              <div class="calendar-content dispersion" :style="{float: this.headStyle.checkBtn}">
                <span class="calendar-prev" @click="handlePrevMonth"> 《《 </span>
                <span class="calendar-next" @click="handleNextMonth"> 》》 </span>
              </div>

            </div>
          </div>
          <div class="cc-calendar" v-loading="loadingWeather">
            <ul class="calendar-week clear">
              <li v-for="(item, index) in calendarTitleArr" :key="index" class="week-item">{{item}}</li>
            </ul>
            <ul class="calendar-view clear">
              <li v-for="(item, index) in visibleCalendar"
                  :key="index"
                  class="date-view"
                  :class="[
                {'month-class': !isCurrentMonth(item.date)},
                {handleDay: item.clickDay}
              ]"
                  @click="handleClickDay(item)"
              >
                <div class="date-view-bg">
                  <weatherbg :temperature="item.temperature" :proportion="proportion(item.indicator[tagIndex])"
                             class="weather-bg"></weatherbg>
                  <span class="date-day" :class="[{'opacity-class': !isCurrentMonth(item.date)}]">
                    {{item.day}}
                  </span>
                  <span class="lunar-day">
                    {{item.lunarDay}}
                  </span>
                  <!--<h3 class="temperature">{{item.temperature}}</h3>-->
                  <p class="weather-text">{{item.weather}} <span v-show="item.weather">/</span>&nbsp;
                    {{item.temperatureNight}}C°</p>
                  <p class="enters">{{tag}} : {{item.indicator[tagIndex]}}人&nbsp;{{proportion(item.indicator[tagIndex])+"%"}}</p>
                </div>
              </li>

            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import moment from "moment";
  import LunarCalendar from "@/tools/LunarCalendar.js";
  import weatherbg from "@/components/analyzeReport/reportpublic/weatherBg"

  const englishMonthList = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
  const calendarArr = {
    type: 'combination',
    date: "",
    headStyle: {
      todayBtn: 'right',
      combination: 'center',
      checkBtn: 'right',
    },
    viewStyle: {
      day: 'right'
    },
    calendarData: []
  };
  const utils = {
    getNewDate(date) {
      let year = date.getFullYear();
      let month = date.getMonth();
      let day = date.getDate();
      return {year, month, day};
    },
    getDate(year, month, day) {
      return new Date(year, month, day);
    },
    englishMonth(month) {
      let engMonth;

      englishMonthList.map(() => {
        engMonth = englishMonthList[month]
      });

      return engMonth
    },
    formatDate(date) {
      date = Number(date);
      return date < 10 ? `0${date}` : date;
    }
  }
  export default {
    name: "weather.vue",
    props: ["keys"],
    components: {
      weatherbg
    },
    data() {
      let {year, month, day} = utils.getNewDate(new Date());
      return {
        tag: "客流",
        tags: [],
        indicator: [],
        loadingWeather: false,
        headStyle: '',
        loadingimg: false,
        headOptions: {
          type: calendarArr.type,
          style: calendarArr.headStyle,
          date: '',
        },
        englishMonthList: englishMonthList,
        calendarTitleArr: [
          '星期日',
          '星期一',
          '星期二',
          '星期三',
          '星期四',
          '星期五',
          '星期六'

        ],
        dateList: [],
        // dataMax: 0,
        time: {year, month, day},
        calendarList: []
      }
    },
    computed: {
      dataMax() {
        let dataMax = 0;
        this.visibleCalendar.forEach(ele => {
          if (ele.indicator[this.tagIndex] > dataMax) {
            dataMax = ele.indicator[this.tagIndex]
          }
        })
        return dataMax;
      },
      tagIndex() {
        return this.tags.indexOf(this.tag)
      },
      visibleCalendar() {
        let maxData = 0;
        let calendatArr = [];

        let {year, month, day} = utils.getNewDate(utils.getDate(this.time.year, this.time.month, 1));

        let currentFirstDay = utils.getDate(year, month, 1);

        let monthSum = parseInt(moment(utils.getDate(this.time.year, this.time.month, 1)).endOf('month').format("DD"))
        // 获取当前月第一天星期几
        let weekDay = currentFirstDay.getDay();

        if (weekDay == 7) weekDay = 0
        let startTime = currentFirstDay - (weekDay) * 24 * 60 * 60 * 1000;
        let monthDayNum;
        if (monthSum + weekDay > 35) {
          monthDayNum = 42
        } else if (monthSum + weekDay > 28) {
          monthDayNum = 35
        } else {
          monthDayNum = 28
        }
        // console.log(weekDay)
        let weatherList = ["晴转阴", "晴", "雨", "阴"]
        for (let i = 0; i < monthDayNum; i++) {

          let date = moment(new Date(startTime + i * 24 * 60 * 60 * 1000));
          let value = 0;
          let weatherStr = "";
          let temperature = 0;
          let temperatureNight = 0;
          let indicator = [0, 0, 0];
          this.dateList.forEach(ele => {
            if (date.format("YYYY-MM-DD") == moment(ele.reporttime).format("YYYY-MM-DD")) {
              value = ele.value
              weatherStr = ele.weather.length <= 3 ? ele.weather.join("转") : ele.weather.join(",")
              temperature = ele.temperature;
              temperatureNight = ele.temperatureNight;
              indicator = ele.indicator;
            }
          })
          if (value > maxData) maxData = value;


          calendatArr.push({
            indicator: indicator,
            date: new Date(startTime + i * 24 * 60 * 60 * 1000),
            year: year,
            month: month + 1,
            day: new Date(startTime + i * 24 * 60 * 60 * 1000).getDate(),
            clickDay: false,
            value: value,
            weather: weatherStr,
            temperature: temperature,
            lunarDay: LunarCalendar.solar2lunar(date.year(),date.month()+1,date.date()).IDayCn,
            temperatureNight: temperatureNight
          })
        }
        ;
        // this.dataMax = maxData;
        this.headOptions.date = `${utils.englishMonth(month)} ${year}`;

        return calendatArr
      }
    },
    mounted() {
      this.$Bus.$on("Loading", (data) => {
        this.loadingWeather = data
      })
      let that = this;
      setTimeout(function () {
        var flag = null;
        window.onresize = function () {
          if (!flag) {
            flag = setTimeout(function () {
              that.$Bus.$emit("onresize")
              clearTimeout(flag);
              flag = null
            }, 1000)
          }
        };
      }, 200)
      // console.log(this.keys);
      this.headStyle = this.headOptions.style;
      // this.getWeather()
    },
    beforeDestroy() {
      window.onresize = null;
    },
    watch: {
      keys(list) {
        let tags = [];
        let indicator = [];
        list.forEach(ele=>{
          indicator.push(ele.key)
          tags.push(ele.name)
        })
        if(tags.length>0)
          this.tag=tags[0];
        this.tags=tags;
        this.indicator=indicator;
      }
    },
    methods: {
      tagChange() {

      },
      proportion(value) {
        // let dataMax=0;
        // this.calendarList.forEach(ele=>{
        //   if(ele.indicator[this.tagIndex]>dataMax){
        //     dataMax=ele.indicator[this.tagIndex]
        //   }
        // })
        // console.log(this.dataMax);
        if (value)
          return parseInt(value / this.dataMax * 100)
        else
          return 0
      },
      getWeather(date, caseId, callback) {

        let indicator = this.indicator;
        let params = {
          org_id_list: [caseId],
          org_type: 2,
        }
        let url = "/sys/weather_report/find_calendar_weather" + this.$api.objToUrl({
          start_day: moment(date).startOf("month").format("YYYY-MM-DD"),
          end_day: moment(date).endOf("month").format("YYYY-MM-DD"),
          group_type: "case",
          indicator_keys: indicator.join()
        })
        // console.log(params,url)
        // return

        this.$api.post(url, params)
          .then(data => {
            let list = [];

            if (data == '10001') {
              this.$message.error('无权操作该数据')
              this.$Bus.$emit('Loading', false)
              setTimeout(()=>{
                this.$Bus.$emit("onresize")
              },100)
              return callback && callback();
            }
            if (data && data.data && data.data.length >= 0) {
              let weatherList = data.data
              for (let i = 0; i < weatherList.length; i++) {
                let weather = weatherList[i];
                let indicatorList = [];

                for (let j = 0; j < indicator.length; j++) {
                  indicatorList.push(weather[indicator[j]]);
                }
                list.push({
                  indicator: indicatorList,
                  value: indicatorList[this.tagIndex],
                  reporttime: weather.reporttime,
                  temperature: weather.temperature,
                  temperatureNight: weather.temperatureNight,
                  weather: weather.weather
                })
              }
              this.dateList = list;
              this.$nextTick(()=>{
                setTimeout(() => {
                  this.$Bus.$emit("onresize")
                }, 200)
              })
            }
            this.$Bus.$emit('Loading', false)
            callback && callback();
          })
          .catch(err => {
            // console.error(err, '企业下无指标');
            callback && callback(err);
            this.$Bus.$emit('Loading', false);
          })
      },
      upData(date, data) {
        // console.log(date,data)
        // return
        setTimeout(() => {
          this.$Bus.$emit("onresize")
        }, 200)
        this.getWeather(date, data.case_id, () => {
          this.time = utils.getNewDate(new Date(date));
        })
      },
      // 是否是当前月
      isCurrentMonth(date) {
        let {year: currentYear, month: currentMonth} = utils.getNewDate(utils.getDate(this.time.year, this.time.month, 1));
        let {year, month} = utils.getNewDate(date);
        return currentYear == year && currentMonth == month
      },
      // 是否是今天
      isCurrentDay(date) {
        let {year: currentYear, month: currentMonth, day: currentDay} = utils.getNewDate(new Date());
        let {year, month, day} = utils.getNewDate(date);
        return currentYear == year && currentMonth == month && currentDay == day;
      },
      // 上一个月
      handlePrevMonth() {
        let prevMonth = utils.getDate(this.time.year, this.time.month, 1);
        prevMonth.setMonth(prevMonth.getMonth() - 1);
        this.time = utils.getNewDate(prevMonth);
        this.headOptions.date = `${utils.englishMonth(this.time.month)} ${this.time.year}`;
      },
      // 下一个月
      handleNextMonth() {
        let nextMonth = utils.getDate(this.time.year, this.time.month, 1);
        nextMonth.setMonth(nextMonth.getMonth() + 1);
        this.time = utils.getNewDate(nextMonth);
        this.headOptions.date = `${utils.englishMonth(this.time.month)} ${this.time.year}`;
      },
      // 点击回到今天
      handleToday() {
        this.time = utils.getNewDate(new Date());

      },
      // 点击某一天
      handleClickDay(item) {
        // console.log(item)
      }
    },
    created() {
      this.calendarList = this.visibleCalendar;
      this.calendarType = calendarArr.calendarType;
    }

  }
</script>

<style scoped lang="scss">
  .heatmap-report {
    width: 100%;
    background: #fff;
    padding: 35px 10px 20px 35px;
    overflow: hidden;
    > h2 {
      line-height: 1;
      font-weight: 600;
      font-size: 20px;
      letter-spacing: 1px;
      display: inline-block;
      margin-right: 20px;
    }
    .echardiv {
      .repData {
        margin: 20px auto 0;
        border: 3px solid #f5f5f5;
        width: 100%;
        border: 0;
        position: relative;
        .zwtp {
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          background: rgba(245, 248, 254, 0.9);
          z-index: 998;
          h3 {
            position: absolute;
            color: #4e4e4e;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            letter-spacing: 3px;
            padding-left: 3px;
          }
        }
        .zwsj {
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          background: rgba(245, 248, 254, 0.9);
          z-index: 998;
          h3 {
            position: absolute;
            color: #414141;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            letter-spacing: 3px;
            padding-left: 3px;
          }
        }
        img {
          width: 100%;
          height: 100%;
          display: block;
          margin: auto;
        }
        .point {
          position: absolute;
          border-radius: 50%;
          display: block;
          cursor: pointer;
          background: rgba(0, 0, 0, 0);
          transform: translate(-50%, -50%);
          z-index: 10;
          p {
            position: absolute;
            left: 90%;
            top: 50%;
            display: none;
            width: 200px;
            background: rgba(0, 0, 0, 0.8);
            padding: 10px 0 10px 20px;
            border-radius: 6px;
            color: #fff;
            > span {
              display: block;
              line-height: 24px;
            }
          }
          &:hover {
            p {
              display: block;
            }
          }
        }
      }
    }
  }

  .cc-calendar {
    padding: 23px 30px 30px;
    width: 100%;
    height: 100%;

    box-sizing: border-box;
    .calendar-header {
      margin-bottom: 23px;
      width: 100%;
      .calendar-box {
        position: relative;
        height: 32px;
        line-height: 32px;
        .calendar-content {
          width: 100%;
          .calendar-prev,
          .calendar-next {
            display: inline-block;
            vertical-align: middle;
            width: 8px;
            height: 11px;
            /*background: url('../assets/img/left.png') no-repeat;*/
            background-size: contain;
            cursor: pointer;
          }
          .calendar-next {
            /*background: url('../assets/img/right.png') no-repeat;*/
            background-size: contain;
          }
        }
        .dispersion {
          width: initial;
          display: inline;
        }
        .calendar-headDate {
          vertical-align: middle;
          margin: 0 12px;
          font-size: 18px;
          color: #424953;
          -webkit-user-select: none;
          -webkit-touch-callout: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
        }
        .calendar-today {
          position: absolute;
          top: 0;
          right: 0;
          width: 80px;
          height: 30px;
          text-align: center;
          border: 1px solid #2061FF;
          border-radius: 4px;
          font-size: 14px;
          color: #2061FF;
          cursor: pointer;
        }
        .dispersion-today {
          position: inherit;
        }
        .calendar-center {
          margin: 0 auto;
        }
        .calendar-left {
          float: left;
        }
        .calendar-right {
          float: right;
        }
      }
    }
    .calendar-week {
      width: 100%;
      height: 46px;
      line-height: 46px;
      border: 1px solid #E4E7EA;
      border-right: none;
      border-top: 0;
      border-left: 0;
      margin-bottom: 25px;
      .week-item {
        float: left;
        width: 14.285%;

        text-align: center;
        font-size: 14px;
        color: #424953;
        border-right: 1px solid #E4E7EA;
        border: none;
        font-weight: 600;

      }
    }
    ul.calendar-view {
      width: 100%;
      .month-class .date-view {
        background: none;
      }
      .date-view {
        float: left;
        width: 14.285%;
        height: 140px;
        border-right: 1px solid #E4E7EA;
        border-bottom: 1px solid #E4E7EA;
        cursor: pointer;
        border: 0;
        color: #190595;
        .weather-text {
          text-align: center;
          font-size: 14px;
          padding-top: 65px;
          position: relative;
          height: 20px;
          display: inline-block;
          text-align: center;
          width: 100%;
        }
        .enters {
          text-align: center;
          margin-top: 15px;
          font-size: 12px;
          position: relative;
          color: #fff;
        }
        .temperature {
          font-size: 26px;
          text-align: center;
          line-height: 1.5;
          padding-top: 20px;
          color: #190595;
        }
        .date-view-bg {
          height: 130px;
          background: #f0f2ff;
          margin: 5px;
          position: relative;
        }
        .weather-bg {
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
        }
        .date-day {
          position: absolute;
          background: #fbc12e;
          width: 40px;
          height: 40px;
          display: block;
          color: #fff;
          display: block;
          font-size: 14px;
          top: 0;
          left: 0;
          padding: 5px;
          text-align: center;
          border-radius: 0px 0px 40px 0px;
        }
        .lunar-day {
          float: right;
          font-size: 14px;
          color: #cdd3f3;

          position: absolute;
          right: 10px;
          top: 10px;
        }
        .calendar-num {

          margin-top: 6px;
          display: block;
          width: 100%;
          text-align: center;
          font-size: 30px;
          color: #424953;
        }
      }
      .opacity-class {
        opacity: .5;
      }
      li.month-class {
        .date-view-bg {
          background-image: linear-gradient(45deg, rgba(000, 000, 000, .03) 25%, transparent 25%, transparent 50%, rgba(000, 000, 000, .03) 50%, rgba(000, 000, 000, .03) 75%, transparent 75%, transparent);
          background-size: 20px 20px;
          font-size: 0px;
          background: none;
          span.date-day {
            font-size: 0;
          }
          *, .date-view-bg {
            font-size: 0px;
            background: none;
            display: none;
          }
          .weather-bg {
            display: none
          }
        }
      }
      .todayBg {
        background: #FFFDEF;
      }
      .handleDay {
        background: #2061FF !important;
        .date-day {
          color: #BCCFFF !important;
        }
        .calendar-num {
          color: #fff !important;
        }
      }
    }
  }
</style>